import 'dart:math';

import 'package:dio/dio.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zentoon_flutter/utils/http_helper.dart';

import '../utils/appsflyer_event_manager.dart';
import '../utils/user_manager.dart';
import 'webview_page.dart';

// Global state Provider (login status, user email)
import '../providers/auth_provider.dart';

// Login form state management
final emailProvider = StateProvider<String>((ref) => '');
final passwordProvider = StateProvider<String>((ref) => '');
final isPasswordVisibleProvider = StateProvider<bool>((ref) => false);
final isLoadingProvider = StateProvider<bool>((ref) => false);

class LoginDialog extends ConsumerStatefulWidget {
  const LoginDialog({super.key});

  @override
  ConsumerState<LoginDialog> createState() => _LoginDialogState();
}

class _LoginDialogState extends ConsumerState<LoginDialog>
    with TickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _opacityAnimation;

  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _forgetEmailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  String? _resetToken;
  String? _newToken;
  // bool isShow = false;

  // 添加密码重置相关状态
  bool showPasswordReset = false;
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  String? newPasswordError;
  String? confirmPasswordError;
  bool _isNewPasswordVisible = false;
  bool _isConfirmPasswordVisible = false;

  @override
  void initState() {
    super.initState();
    // _getComicType();
    _initAnimations();
  }

  // Future<void> _getComicType() async {
  //   final prefs = await SharedPreferences.getInstance();
  //   final userType = prefs.getString('user_type');

  //   print("dsfsfdsfdsfsdf = $userType");

  //   if (userType == null ||
  //       userType == 'organic' ||
  //       userType.isEmpty ||
  //       userType == 'Organic') {
  //     setState(() {
  //       isShow = true;
  //     });
  //   }
  // }

  @override
  void dispose() {
    _animationController.dispose();
    _emailController.dispose();
    _passwordController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  // 初始化动画
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
      lowerBound: 0.0,
      upperBound: 1.0,
    );

    _scaleAnimation = Tween<double>(begin: 0.7, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOutBack),
    );

    _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOut),
    );

    if (_animationController.status != AnimationStatus.forward) {
      _animationController.forward();
    }
  }

  Future<void> _visitorLogin() async {
    // 随机生成三位数字
    final random = Random();
    final randomNumber = random.nextInt(900) + 100; // 生成100-999之间的随机数

    String email = '${randomNumber}919143@qq.com';
    const password = 'qwerasd';
    EasyLoading.show();
    // 使用AuthProvider进行登录
    final success =
        await ref.read(authProvider.notifier).login(email, password);
    EasyLoading.dismiss();
    if (success && mounted) {
      _showFeedback('Login successful!', FeedbackType.success);
      _closeDialog();

      await AppsFlyerEventManager.logRegistration(
        method: 'email',
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final isPasswordVisible = ref.watch(isPasswordVisibleProvider);
    final isLoading = ref.watch(isLoadingProvider);

    return AnimatedBuilder(
      animation: _animationController,
      builder: (context, child) {
        return Opacity(
          opacity: _opacityAnimation.value,
          child: GestureDetector(
            onTap: () {
              // Hide keyboard when clicking background, but don't close dialog
              FocusScope.of(context).unfocus();
            },
            child: Container(
              color: Colors.transparent,
              constraints: const BoxConstraints.expand(),
              child: Center(
                child: GestureDetector(
                  onTap: () {
                    // Hide keyboard when clicking dialog content area
                    FocusScope.of(context).unfocus();
                  },
                  child: Transform.scale(
                    scale: _scaleAnimation.value,
                    child: Material(
                      color: Colors.transparent,
                      elevation: 0,
                      child: SingleChildScrollView(
                        physics: const BouncingScrollPhysics(),
                        padding: EdgeInsets.only(
                          bottom: MediaQuery.of(context)
                              .viewInsets
                              .bottom, // Keyboard height
                        ),
                        child: Center(
                          child: Container(
                            width: MediaQuery.of(context).size.width < 320
                                ? 280
                                : MediaQuery.of(context).size.width * 0.85,
                            // Use maxHeight here, don't force minHeight
                            constraints: BoxConstraints(
                              maxHeight:
                                  MediaQuery.of(context).size.height * 0.8,
                            ),
                            margin: const EdgeInsets.symmetric(horizontal: 20),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: const Color(0xFF2A1F3D),
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.3),
                                  blurRadius: 15,
                                  offset: const Offset(0, 8),
                                ),
                              ],
                            ),
                            child: Stack(
                              children: [
                                // Close button
                                Positioned(
                                  top: 12,
                                  right: 12,
                                  child: GestureDetector(
                                    onTap: _closeDialog,
                                    child: Container(
                                      width: 32,
                                      height: 32,
                                      decoration: BoxDecoration(
                                        color: Colors.white.withOpacity(0.1),
                                        borderRadius: BorderRadius.circular(16),
                                      ),
                                      child: const Icon(
                                        Icons.close,
                                        color: Colors.white70,
                                        size: 20,
                                      ),
                                    ),
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(24),
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      const Padding(
                                        padding:
                                            EdgeInsets.symmetric(vertical: 24),
                                        child: Text(
                                          'LOGIN / SIGN UP',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 22,
                                            fontWeight: FontWeight.bold,
                                            letterSpacing: 1.2,
                                          ),
                                        ),
                                      ),
                                      Column(
                                        mainAxisSize: MainAxisSize.min,
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          // Email input field
                                          const Text(
                                            'Email',
                                            style: TextStyle(
                                              color: Colors.white70,
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          const SizedBox(height: 8),
                                          Container(
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              boxShadow: [
                                                BoxShadow(
                                                  color: Colors.black
                                                      .withOpacity(0.1),
                                                  blurRadius: 4,
                                                  offset: const Offset(0, 2),
                                                ),
                                              ],
                                            ),
                                            child: TextField(
                                              controller: _emailController,
                                              keyboardType:
                                                  TextInputType.emailAddress,
                                              autocorrect: false,
                                              enableSuggestions: false,
                                              decoration: const InputDecoration(
                                                border: InputBorder.none,
                                                contentPadding:
                                                    EdgeInsets.symmetric(
                                                  horizontal: 16,
                                                  vertical: 12,
                                                ),
                                                hintText: 'Enter your email',
                                                hintStyle: TextStyle(
                                                  color: Colors.grey,
                                                  fontSize: 14,
                                                ),
                                              ),
                                              // onChanged: (value) {
                                              //   ref
                                              //       .read(
                                              //           emailProvider.notifier)
                                              //       .state = value;
                                              //   _validateEmail(value);
                                              // },
                                            ),
                                          ),

                                          const SizedBox(height: 16),

                                          // Password input field
                                          const Text(
                                            'Password',
                                            style: TextStyle(
                                              color: Colors.white70,
                                              fontSize: 14,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          const SizedBox(height: 8),
                                          Container(
                                            decoration: BoxDecoration(
                                              color: Colors.white,
                                              borderRadius:
                                                  BorderRadius.circular(8),
                                              boxShadow: [
                                                BoxShadow(
                                                  color: Colors.black
                                                      .withOpacity(0.1),
                                                  blurRadius: 4,
                                                  offset: const Offset(0, 2),
                                                ),
                                              ],
                                            ),
                                            child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                TextField(
                                                  controller:
                                                      _passwordController,
                                                  enableSuggestions: false,
                                                  autocorrect: false,
                                                  decoration: InputDecoration(
                                                    border: InputBorder.none,
                                                    contentPadding:
                                                        const EdgeInsets
                                                            .symmetric(
                                                      horizontal: 16,
                                                      vertical: 12,
                                                    ),
                                                    hintText:
                                                        'Enter your password',
                                                    hintStyle: const TextStyle(
                                                      color: Colors.grey,
                                                      fontSize: 14,
                                                    ),
                                                    suffixIcon: GestureDetector(
                                                      onTap: () {
                                                        ref
                                                                .read(isPasswordVisibleProvider
                                                                    .notifier)
                                                                .state =
                                                            !isPasswordVisible;
                                                      },
                                                      child: const Padding(
                                                        padding: EdgeInsets
                                                            .symmetric(
                                                                horizontal: 12),
                                                        child: Icon(
                                                          Icons.visibility,
                                                          color: Colors.grey,
                                                          size: 20,
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),

                                          const SizedBox(height: 20),

                                          // Login button
                                          SizedBox(
                                            width: double.infinity,
                                            height: 48,
                                            child: ElevatedButton(
                                              onPressed: isLoading
                                                  ? null
                                                  : _handleLogin,
                                              style: ElevatedButton.styleFrom(
                                                backgroundColor:
                                                    const Color(0xFF7B68EE),
                                                foregroundColor: Colors.white,
                                                shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(8),
                                                ),
                                                elevation: 3,
                                                disabledBackgroundColor:
                                                    const Color(0xFF7B68EE)
                                                        .withOpacity(0.6),
                                              ),
                                              child: isLoading
                                                  ? const SizedBox(
                                                      height: 20,
                                                      width: 20,
                                                      child:
                                                          CircularProgressIndicator(
                                                        strokeWidth: 2,
                                                        valueColor:
                                                            AlwaysStoppedAnimation<
                                                                    Color>(
                                                                Colors.white),
                                                      ),
                                                    )
                                                  : const Text(
                                                      'Log In / Sign Up',
                                                      style: TextStyle(
                                                        fontSize: 16,
                                                        fontWeight:
                                                            FontWeight.bold,
                                                      ),
                                                    ),
                                            ),
                                          ),

                                          const SizedBox(height: 16),

                                          // User agreement and privacy policy
                                          Padding(
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 8),
                                            child: RichText(
                                              textAlign: TextAlign.center,
                                              text: TextSpan(
                                                style: TextStyle(
                                                  color: Colors.white
                                                      .withOpacity(0.7),
                                                  fontSize: 12,
                                                ),
                                                children: [
                                                  const TextSpan(
                                                      text:
                                                          'By signing up, you agree to our '),
                                                  TextSpan(
                                                    text: 'Terms of Service',
                                                    style: const TextStyle(
                                                      decoration: TextDecoration
                                                          .underline,
                                                      color: Color(0xFF7B68EE),
                                                    ),
                                                    recognizer:
                                                        TapGestureRecognizer()
                                                          ..onTap =
                                                              _openTermsOfService,
                                                  ),
                                                  const TextSpan(text: ' and '),
                                                  TextSpan(
                                                    text: 'Privacy Policy',
                                                    style: const TextStyle(
                                                      decoration: TextDecoration
                                                          .underline,
                                                      color: Color(0xFF7B68EE),
                                                    ),
                                                    recognizer:
                                                        TapGestureRecognizer()
                                                          ..onTap =
                                                              _openPrivacyPolicy,
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),

                                          const SizedBox(height: 12),

                                          // Forgot password link
                                          Center(
                                            child: TextButton(
                                              onPressed: _handleForgotPassword,
                                              style: TextButton.styleFrom(
                                                padding: EdgeInsets.zero,
                                                minimumSize: const Size(50, 30),
                                                tapTargetSize:
                                                    MaterialTapTargetSize
                                                        .shrinkWrap,
                                              ),
                                              child: Text(
                                                'Forget password?',
                                                style: TextStyle(
                                                  color: Colors.white
                                                      .withOpacity(0.7),
                                                  fontSize: 14,
                                                  decoration:
                                                      TextDecoration.underline,
                                                  decorationColor: Colors.white
                                                      .withOpacity(0.7),
                                                ),
                                              ),
                                            ),
                                          ),

                                          const SizedBox(
                                            height: 24,
                                          ),
                                          Center(
                                            child: GestureDetector(
                                              onTap: () {
                                                _visitorLogin();
                                              },
                                              child: const Text(
                                                'Visitor Login',
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 18,
                                                  decoration:
                                                      TextDecoration.underline,
                                                  decorationColor: Colors.white,
                                                ),
                                              ),
                                            ),
                                          )
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // Close dialog
  void _closeDialog() {
    if (mounted) {
      Navigator.of(context).pop();
    }
  }

  // Handle login logic
  Future<void> _handleLogin() async {
    final email = _emailController.text.trim();
    final password = _passwordController.text.trim();

    // 使用AuthProvider进行登录
    final success =
        await ref.read(authProvider.notifier).login(email, password);

    if (success && mounted) {
      _showFeedback('Login successful!', FeedbackType.success);
      _closeDialog();

      await AppsFlyerEventManager.logRegistration(
        method: 'email',
      );
    }
  }

  // Validate email
  bool _validateEmail(String email) {
    if (email.isEmpty) {
      return true;
    }

    if (_isValidEmail(email)) {
      return true;
    } else {
      return false;
    }
  }

  // Email format validation
  bool _isValidEmail(String email) {
    return RegExp(
      r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
    ).hasMatch(email);
  }

  // Handle forgot password
  // Add state variables in _handleForgotPassword method
  void _handleForgotPassword() {
    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        String recoveryEmail = '';
        bool isLoading = false;
        String? emailError;
        bool showCodeInput =
            false; // New: control whether to show verification code input
        String verificationCode = '';
        String? codeError;
        final TextEditingController recoveryEmailController =
            TextEditingController();
        final TextEditingController codeController = TextEditingController();

        return StatefulBuilder(
          builder: (context, setState) {
            return Dialog(
              backgroundColor: Colors.transparent,
              child: Container(
                width: MediaQuery.of(context).size.width * 0.85,
                padding: const EdgeInsets.all(24),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: const Color(0xFF2A1F3D),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 15,
                      offset: const Offset(0, 8),
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // Back button
                    Row(
                      children: [
                        GestureDetector(
                          onTap: () => Navigator.of(context).pop(),
                          child: Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: const Icon(
                              Icons.arrow_back,
                              color: Colors.white70,
                              size: 20,
                            ),
                          ),
                        ),
                        const Spacer(),
                      ],
                    ),

                    const SizedBox(height: 20),

                    const Text(
                      'PASSWORD RECOVERY',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 1.2,
                      ),
                    ),

                    const SizedBox(height: 16),

                    const Text(
                      'Enter your email to recovery your password.',
                      style: TextStyle(
                        color: Color(0xFFB8B3C7),
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                    ),

                    const SizedBox(height: 24),

                    // Email label
                    const Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Email',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),

                    const SizedBox(height: 8),

                    // Email input field (hidden during password reset)
                    if (!showPasswordReset) ...[
                      Container(
                        decoration: BoxDecoration(
                          color: const Color(0xFF3D2F5A),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: const Color(0xFF5A4B7C),
                            width: 1,
                          ),
                        ),
                        child: TextField(
                          autocorrect: false,
                          enableSuggestions: false,
                          controller: recoveryEmailController,
                          enabled:
                              !showCodeInput, // Disable email input after successful sending
                          keyboardType: TextInputType.emailAddress,
                          style: TextStyle(
                            color:
                                showCodeInput ? Colors.white54 : Colors.white,
                            fontSize: 14,
                          ),
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 12,
                            ),
                            hintText: 'Enter your email',
                            hintStyle: TextStyle(
                              color: Color(0xFF8A7CA8),
                              fontSize: 14,
                            ),
                          ),
                        ),
                      ),
                    ],

                    // Verification code input field (conditionally shown, hidden during password reset)
                    if (showCodeInput && !showPasswordReset) ...[
                      const SizedBox(height: 16),
                      const Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          'Verification Code',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      const SizedBox(height: 8),
                      Container(
                        decoration: BoxDecoration(
                          color: const Color(0xFF3D2F5A),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: const Color(0xFF5A4B7C),
                            width: 1,
                          ),
                        ),
                        child: TextField(
                          controller: codeController,
                          keyboardType: TextInputType.number,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 12,
                            ),
                            hintText: 'Enter verification code',
                            hintStyle: const TextStyle(
                              color: Color(0xFF8A7CA8),
                              fontSize: 14,
                            ),
                            errorText: codeError,
                            errorStyle: const TextStyle(
                              color: Color(0xFFFF6B6B),
                              fontSize: 12,
                            ),
                          ),
                          onChanged: (value) {
                            verificationCode = value;
                          },
                        ),
                      ),
                    ],

                    const SizedBox(height: 24),

                    // Password reset UI (shown after successful verification code verification)
                    if (showPasswordReset) ...[
                      // Add title
                      const Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          'Set New Password',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      const SizedBox(height: 16),
                      const SizedBox(height: 16),

                      // New password input field
                      const Text(
                        'New Password',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Container(
                        decoration: BoxDecoration(
                          color: const Color(0xFF3D2F5A),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: const Color(0xFF5A4B7C),
                            width: 1,
                          ),
                        ),
                        child: TextField(
                          controller: _newPasswordController,
                          obscureText: !_isNewPasswordVisible,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 12,
                            ),
                            hintText: 'Enter new password',
                            hintStyle: const TextStyle(
                              color: Color(0xFF8A7CA8),
                              fontSize: 14,
                            ),
                            errorText: newPasswordError,
                            errorStyle: const TextStyle(
                              color: Color(0xFFFF6B6B),
                              fontSize: 12,
                            ),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _isNewPasswordVisible
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                                color: const Color(0xFF8A7CA8),
                                size: 20,
                              ),
                              onPressed: () {
                                setState(() {
                                  _isNewPasswordVisible =
                                      !_isNewPasswordVisible;
                                });
                              },
                            ),
                          ),
                          onChanged: (value) {
                            setState(() {
                              newPasswordError = null;
                            });
                          },
                        ),
                      ),

                      const SizedBox(height: 16),

                      // Confirm password input field
                      const Text(
                        'Confirm Password',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Container(
                        decoration: BoxDecoration(
                          color: const Color(0xFF3D2F5A),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: const Color(0xFF5A4B7C),
                            width: 1,
                          ),
                        ),
                        child: TextField(
                          controller: _confirmPasswordController,
                          obscureText: !_isConfirmPasswordVisible,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                          ),
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 12,
                            ),
                            hintText: 'Confirm new password',
                            hintStyle: const TextStyle(
                              color: Color(0xFF8A7CA8),
                              fontSize: 14,
                            ),
                            errorText: confirmPasswordError,
                            errorStyle: const TextStyle(
                              color: Color(0xFFFF6B6B),
                              fontSize: 12,
                            ),
                            suffixIcon: IconButton(
                              icon: Icon(
                                _isConfirmPasswordVisible
                                    ? Icons.visibility
                                    : Icons.visibility_off,
                                color: const Color(0xFF8A7CA8),
                                size: 20,
                              ),
                              onPressed: () {
                                setState(() {
                                  _isConfirmPasswordVisible =
                                      !_isConfirmPasswordVisible;
                                });
                              },
                            ),
                          ),
                          onChanged: (value) {
                            setState(() {
                              confirmPasswordError = null;
                            });
                          },
                        ),
                      ),
                    ],

                    const SizedBox(height: 24),

                    // Button (shows different text based on state)
                    SizedBox(
                      width: double.infinity,
                      height: 48,
                      child: ElevatedButton(
                        onPressed: isLoading
                            ? null
                            : () async {
                                if (!showCodeInput) {
                                  // Step 1: Send verification code
                                  final email =
                                      recoveryEmailController.text.trim();

                                  if (email.isEmpty) {
                                    _showFeedback('Please enter your email',
                                        FeedbackType.info);
                                    return;
                                  }

                                  if (!_isValidEmail(email)) {
                                    _showFeedback('Please enter a valid email',
                                        FeedbackType.info);
                                    return;
                                  }

                                  setState(() => isLoading = true);

                                  try {
                                    final token =
                                        await _sendPasswordResetEmail(email);
                                    if (token.isNotEmpty) {
                                      // 存储token供后续验证使用
                                      _resetToken = token;
                                      // 发送成功后显示验证码输入框
                                      setState(() {
                                        showCodeInput = true;
                                        emailError = null;
                                      });
                                      _showFeedback(
                                          'Verification code sent to your email!',
                                          FeedbackType.success);
                                    } else {
                                      _showFeedback(
                                          'Failed to send verification code',
                                          FeedbackType.error);
                                    }
                                  } catch (e) {
                                    _showFeedback(
                                        e.toString(), FeedbackType.error);
                                  } finally {
                                    setState(() => isLoading = false);
                                  }
                                } else if (showPasswordReset) {
                                  // Step 3: Reset password
                                  final newPassword =
                                      _newPasswordController.text.trim();
                                  final confirmPassword =
                                      _confirmPasswordController.text.trim();

                                  // 验证密码
                                  if (newPassword.isEmpty) {
                                    setState(() {
                                      newPasswordError =
                                          'Please enter new password';
                                    });
                                    return;
                                  }

                                  if (newPassword.length < 6) {
                                    setState(() {
                                      newPasswordError =
                                          'Password must be at least 6 characters';
                                    });
                                    return;
                                  }

                                  if (confirmPassword.isEmpty) {
                                    setState(() {
                                      confirmPasswordError =
                                          'Please confirm your password';
                                    });
                                    return;
                                  }

                                  if (newPassword != confirmPassword) {
                                    setState(() {
                                      confirmPasswordError =
                                          'Passwords do not match';
                                    });
                                    return;
                                  }

                                  setState(() => isLoading = true);

                                  try {
                                    await _resetPassword(
                                        newPassword, confirmPassword);
                                    if (mounted) {
                                      Navigator.of(context).pop();
                                      _showFeedback(
                                          'Password reset successful!',
                                          FeedbackType.success);
                                    }
                                  } catch (e) {
                                    _showFeedback(
                                        'Failed to reset password: ${e.toString()}',
                                        FeedbackType.error);
                                  } finally {
                                    setState(() => isLoading = false);
                                  }
                                } else {
                                  print("objectsss");
                                  // Step 2: Verify verification code
                                  if (verificationCode.isEmpty) {
                                    _showFeedback(
                                        'Please enter verification code',
                                        FeedbackType.info);
                                    return;
                                  }

                                  setState(() => isLoading = true);

                                  try {
                                    print(
                                        "verificationCode = $verificationCode");
                                    // Pass the stored token
                                    await _verifyResetCode(
                                        verificationCode,
                                        recoveryEmailController.text.trim(),
                                        _resetToken);

                                    // 验证成功后显示密码重置UI
                                    setState(() {
                                      showPasswordReset = true;
                                      codeError = null;
                                    });

                                    _showFeedback(
                                        'Verification successful! Please set your new password.',
                                        FeedbackType.success);
                                  } catch (e) {
                                    setState(() => codeError =
                                        'Invalid verification code');
                                    _showFeedback('Invalid verification code',
                                        FeedbackType.error);
                                  } finally {
                                    setState(() => isLoading = false);
                                  }
                                }
                              },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF7B68EE),
                          foregroundColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                          elevation: 2,
                        ),
                        child: isLoading
                            ? const SizedBox(
                                height: 20,
                                width: 20,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                      Colors.white),
                                ),
                              )
                            : Text(
                                showCodeInput ? 'Verify Code' : 'Send Code',
                                style: const TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

// Add verification code verification method
  Future<void> _verifyResetCode(
      String code, String email, String? resetToken) async {
    try {
      // Use the passed resetToken, if not available use current user token
      final token = resetToken ?? await UserManager.getCurrentToken();

      final requestData = {'email': email, 'code': code, 'token': token};
      print("requestData = $requestData");

      final response = await HttpUtil().postJson(
        'ComicMember/VerifyEmail',
        data: requestData,
      );

      if (response != null && response['status'] == 200) {
        // Verification successful, get new token
        final newToken = response['result']?['token'];
        if (newToken != null) {
          // Save new token

          // Show password reset interface
          setState(() {
            showPasswordReset = true;
            // showCodeInput = false;
          });

          _newToken = newToken;
          // Use UserManager to uniformly manage token storage
          await UserManager.saveToken(_newToken ?? '');
        }
      } else {
        throw Exception(
            response?['message'] ?? 'Verification code verification failed');
      }
    } catch (e) {
      print('Verification code verification error: $e');
      throw Exception('Verification code verification failed: ${e.toString()}');
    }
  }

  Future<void> _resetPassword(String password, String confirmPassword) async {
    try {
      if (_newToken == null) {
        throw Exception('Token does not exist, please re-verify');
      }

      final requestData = {
        'password': password,
        'confirmPassword': confirmPassword,
      };

      final response = await HttpUtil().postJson(
        'ComicMember/ResetPassword',
        data: requestData,
      );

      if (response != null && response['status'] == 200) {
        // Reset successful, clear all tokens
        await UserManager.clearLoginInfo();
        _resetToken = null;
        _newToken = null;

        if (mounted) {
          Navigator.of(context).pop();
          _showFeedback(
              'Password reset successful! Please login with your new password.',
              FeedbackType.success);
        }
      } else {
        throw Exception(response?['message'] ?? 'Password reset failed');
      }
    } catch (e) {
      print('Password reset error: $e');
      throw Exception('Password reset failed: ${e.toString()}');
    }
  }

  bool _validatePasswords() {
    setState(() {
      newPasswordError = null;
      confirmPasswordError = null;
    });

    final password = _newPasswordController.text.trim();
    final confirmPassword = _confirmPasswordController.text.trim();

    if (password.isEmpty) {
      setState(() => newPasswordError = 'Please enter new password');
      return false;
    }

    if (password.length < 6) {
      setState(
          () => newPasswordError = 'Password must be at least 6 characters');
      return false;
    }

    if (confirmPassword.isEmpty) {
      setState(() => confirmPasswordError = 'Please confirm your password');
      return false;
    }

    if (password != confirmPassword) {
      setState(() => confirmPasswordError = 'Passwords do not match');
      return false;
    }

    return true;
  }

  // Send password reset email
  Future<String> _sendPasswordResetEmail(String email) async {
    print("=== Send email debug info ===");
    print("Email address: '$email'");

    if (email.isEmpty) {
      print("Error: Email address is empty");
      throw Exception('Email address cannot be empty');
    }

    final requestData = {'email': email};
    print("Request data: $requestData");

    try {
      // Create a temporary Dio instance without Authorization header
      final tempDio = Dio(BaseOptions(
        baseUrl: 'https://api.misstory789.online/api/asf/',
        connectTimeout: const Duration(seconds: 5),
        receiveTimeout: const Duration(seconds: 3),
        contentType: 'application/json-patch+json',
        validateStatus: (status) => status != null,
      ));

      final response = await tempDio.post(
        'ComicMember/SendEmail',
        data: requestData,
      );

      print("Response result: ${response.data}");
      print("Response status code: ${response.statusCode}");

      if (response.statusCode == 200 && response.data != null) {
        // Safely handle response data
        final responseData = response.data;
        print("Parse response data: $responseData");

        // Check business status code
        if (responseData['status'] == 200) {
          // Successfully sent email
          final result = responseData['result'];
          if (result != null) {
            print("Email sent successfully, token: $result");
            return result.toString();
          }
          return "";
        } else {
          // Handle business errors
          final message = responseData['message'] ?? 'Failed to send email';
          print("Business error: ${responseData['status']}, message: $message");

          if (responseData['status'] == 1004) {
            // Send frequency limit
            throw Exception(
                'Please wait 20 seconds before requesting another code');
          } else {
            throw Exception(message);
          }
        }
      } else {
        throw Exception('Failed to send verification code');
      }
    } catch (e) {
      print("Request exception: $e");
      throw Exception(e.toString());
    }
  }

  // Open user agreement page
  void _openTermsOfService() {
    _navigateToWebView('User Agreement',
        'https://www.privacypolicies.com/live/01b48fbe-048a-4c57-b276-41d5c1e8e789');
  }

  // Open privacy policy page
  void _openPrivacyPolicy() {
    _navigateToWebView('Privacy Policy',
        'https://www.privacypolicies.com/live/01b48fbe-048a-4c57-b276-41d5c1e8e789');
  }

  // Navigate to WebView page
  void _navigateToWebView(String title, String url) {
    if (mounted) {
      Navigator.of(context).push(
        MaterialPageRoute(
          builder: (context) => WebViewPage(title: title, url: url),
        ),
      );
    }
  }

  // Unified feedback prompt method
  void _showFeedback(String message, FeedbackType type) {
    if (!mounted) return;

    switch (type) {
      case FeedbackType.info:
        EasyLoading.showInfo(message);
        break;
      case FeedbackType.success:
        EasyLoading.showSuccess(message);
        break;
      case FeedbackType.error:
        EasyLoading.showError(message);
        break;
    }
  }
}

// Feedback type enumeration
enum FeedbackType {
  info,
  success,
  error,
}
